package com.inetools.gwetons.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SimpleHtmlSanitizer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class ExceptionReporter {
	private static DialogBox dialogBox = new DialogBox(true, true);

	public ExceptionReporter() {
	}

	private static int width = Window.getClientWidth() / 2;
	
	public static void showException(String messageHtmlStr, Throwable throwable)
			throws IllegalArgumentException {
		boolean isMessageHtmlStrValid = true;
		if ((messageHtmlStr == null) || ("".equals(messageHtmlStr))) {
			isMessageHtmlStrValid = false;
		}

		boolean isThrowableValid = true;
		if (throwable == null) {
			if (isMessageHtmlStrValid)
				throw new IllegalArgumentException(
						"One of the arguments either messageHtmlStr or throwable needs to contain the substantial information.");
			isThrowableValid = false;
		}

		VerticalPanel verticalPanel = new VerticalPanel();
		if (isMessageHtmlStrValid) {
			verticalPanel.add( new HTML( SimpleHtmlSanitizer.sanitizeHtml( messageHtmlStr)));
		}
		if (isThrowableValid) {
			VerticalPanel throwableVerticalPanel = new VerticalPanel();

			throwableVerticalPanel.add(new Label(throwable
					.getLocalizedMessage()));
			
			SafeHtmlBuilder safeHtmlBuilder = new SafeHtmlBuilder();
			safeHtmlBuilder.appendHtmlConstant( "<pre>"); 
			for (StackTraceElement stackTraceElement : throwable.getStackTrace()) {
				safeHtmlBuilder.appendEscaped( stackTraceElement.toString());
				safeHtmlBuilder.appendHtmlConstant( "<br />");
			} // for
			safeHtmlBuilder.appendHtmlConstant( "<pre>"); 
			throwableVerticalPanel.add(new HTML( safeHtmlBuilder.toSafeHtml()));

			verticalPanel.add(throwableVerticalPanel);
		}

		dialogBox.clear();
GWT.log( "width = " + width, null);
		if ( width > 300) {
			dialogBox.setWidth( String.valueOf(width) + "px");
		}
		dialogBox.add( new ScrollPanel( verticalPanel));
		dialogBox.center();
		dialogBox.show();
	} // public static void showException( String messageHtmlStr, Throwable
		// throwable)
}
